//
//  UTOTP.m
//  OTPGenerator
//
//  Created by 武探 on 2017/3/30.
//  Copyright © 2017年 wutan. All rights reserved.
//

#import "UTOTP.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation UTOTP

-(instancetype)initWithConfiguration:(UTOTPConfiguration *)configuration {
    self = [super init];
    if(self) {
        _configuration = configuration;
    }
    return self;
}

-(NSString *)generateOTP {
    [self doesNotRecognizeSelector:_cmd];
    return nil;
}

-(NSString *)generateOTPForCounter:(uint64_t)counter {
    CCHmacAlgorithm alg = kCCHmacAlgSHA1;
    NSUInteger hashLength = CC_SHA1_DIGEST_LENGTH;
    
    NSMutableData *hash = [NSMutableData dataWithLength:hashLength];
    
    UTOTPConfiguration *config = self.configuration;
    
    counter = NSSwapHostLongLongToBig(counter);
    NSData *counterData = [NSData dataWithBytes:&counter
                                         length:sizeof(counter)];
    CCHmacContext ctx;
    CCHmacInit(&ctx, alg, [config.secret bytes], [config.secret length]);
    CCHmacUpdate(&ctx, [counterData bytes], [counterData length]);
    CCHmacFinal(&ctx, [hash mutableBytes]);
    
    const char *ptr = [hash bytes];
    char const offset = ptr[hashLength-1] & 0x0f;
    uint32_t truncatedHash =
    NSSwapBigIntToHost(*((uint32_t *)&ptr[offset])) & 0x7fffffff;
    uint32_t pinValue = truncatedHash % config.digitsMod;
    
    return [NSString stringWithFormat:@"%0*d", config.digits, pinValue];
}

@end
